<?php


namespace common\behavior;

use common\model\NoteModel;
use common\model\UserModel;
use common\service\NoteService;
use Webman\Stomp\Client;

/**
 * 需求新评论 推送新消息通知
 */
class NoteCommentNotifyDemandRelatedPeopleBehavior
{

    public function run($params)
    {
        $data = $params['record']['data'];

        if (empty($data['demand_type']) || $data['demand_type'] != 'comment') {
            return;
        }
        if (empty($data['comment_subject_id'])) {
            return;
        }
        $commentUser = model(UserModel::class)->where(['id' => $data['created_by']])->find();

        $note = model(NoteModel::class)->find($data['comment_subject_id']);
        if (empty($note)) {
            return;
        }
        $unionIdList = NoteService::getInstance()->getDemandRelatePeople($note, false);
        $notifyParam = [
            'first' => "需求" . mb_substr($note['text'], 0, 15) . " 有新的评论",
            'remark' => "请及时查看",
            'comment_content' => mb_substr($data['text'], 0, 100),
            'comment_at' => date("Y/m/d H:i:s", $data['created']),
            'comment_user_name' => $commentUser['name'],
            'tenant_id' => $data['tenant_id'],
            'demand_id' => $data['comment_subject_id'],
            'project_id' => $data['project_id'],
            'module_code' => $data['module_code'],
            'message_key' => 'demand_has_new_comment',
        ];
        $templateId = NoteService::getInstance()->getDemandCommentAddTemplateId();
        foreach ($unionIdList as $unionId) {
            if ($unionId == $commentUser['union_id']) {
                continue;
            }
            Client::send("send_notify_message_v2", build_queue_data_with_xu([
                "param" => $notifyParam,
                'receiver' => $unionId,
                'template_id' => $templateId,
                'content_type' => 'card_message',
                'notice_type' => 'message_demand',
                'is_popup' => 1,
                'message_key' => 'demand_has_new_comment',
                'project_id' => $note['project_id'],
            ]));
        }
    }
}
